import '../prompt/prompt.css'
import Prompt from '../prompt/prompt.js'
import util from '../util.js'
import BasePlot from './basePlot';
/**
 * 扇形标绘类（支持标绘后编辑位置和大小）
 * @class
 * @augments BasePlot
 * @alias BasePlot.CreateSector
 */
class CreateSector extends BasePlot {
  constructor(viewer, style) {
    super(viewer, style);
    this.type = "sector";
    this.viewer = viewer;
    this.style = style;

    /**
     * @property {Cesium.Entity} centerPoint 扇形中心点实体点（编辑控制点）
     */
    this.centerPoint = null;

    /**
     * @property {Cesium.Entity} edgePoint 扇形边缘点实体点（控制半径）
     */
    this.edgePoint = null;

    /**
     * @property {Cesium.Entity} anglePoint 扇形角度控制实体点（控制角度范围）
     */
    this.anglePoint = null;

    /**
     * @property {Cesium.Cartesian3} center 扇形中心点坐标
     */
    this.center = null;

    /**
     * @property {Cesium.Cartesian3} edge 扇形边缘点坐标
     */
    this.edge = null;

    /**
     * @property {Cesium.Cartesian3} angle 扇形角度控制坐标
     */
    this.angle = null;

    /**
     * @property {Number} radius 扇形半径
     */
    this.radius = 0;

    /**
     * @property {Number} startAngle 扇形起始角度（弧度）
     */
    this.startAngle = 0;

    /**
     * @property {Number} endAngle 扇形结束角度（弧度）
     */
    this.endAngle = 0;

    this.modifyPoint = null; // 当前拖拽的控制点
    this.pointArr = []; // 控制点集合
    this.modifyHandler = null; // 编辑事件处理器
    this.prompt = null; // 提示框
    this.promptStyle = { show: true }; // 提示框样式
    this.isDrawing = false; // 标记是否正在绘制
    this.isSettingRadius = false; // 标记是否正在设置半径
    this.isSettingAngle = false; // 标记是否正在设置角度
    this.lastMousePosition = null; // 记录最后鼠标位置
    this.clickHandler = null; // 点击事件处理器
    this.surfaceClickHandler = null; // 地球表面点击事件处理器

    this.events = {
      startEdit: [],
      endEdit: [],
      endCreate: []
    };
  }

  /**
   * 事件绑定
   * @param {String} type 事件类型（startEdit 开始编辑时 / endEdit 编辑结束时 / endCreate 创建完成后）
   * @param {Function} fun 绑定函数
   */
  on(type, fun) {
    if (this.events[type]) {
      this.events[type].push(fun);
    }
  }

  /**
   * 触发事件
   * @param {String} type 事件类型
   * @param {...any} args 事件参数
   */
  trigger(type, ...args) {
    if (this.events[type]) {
      this.events[type].forEach(fun => fun(...args));
    }
  }

  /**
   * 开始标绘扇形
   * @param {Function} callback 标绘完成回调函数
   */
  start(callback) {
    if (!this.prompt && this.promptStyle.show) {
      this.prompt = new Prompt(this.viewer, this.promptStyle);
    }
    this.state = "startCreate";
    this.isDrawing = true;
    this.isSettingRadius = false;
    this.isSettingAngle = false;
    const that = this;

    // 初始化绘制事件处理器
    if (!this.handler) {
      this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    }

    // 左键按下事件 - 开始设置半径或角度
    this.handler.setInputAction(function (evt) {
      that.lastMousePosition = evt.position;
      const cartesian = that.getCatesian3FromPX(evt.position, that.viewer, []);

      // 检查是否获得有效坐标
      if (!cartesian || that.hasNaNComponent(cartesian)) {
        console.warn('无效坐标，忽略操作');
        return;
      }

      if (!that.centerPoint) {
        // 第一点：中心点
        that.center = cartesian;
        that.centerPoint = that.createPoint(cartesian);
        that.centerPoint.typeAttr = "center";
        that.edgePoint = that.createPoint(cartesian.clone());
        that.edge = cartesian.clone();
        that.edgePoint.typeAttr = "edge";
        that.anglePoint = that.createPoint(cartesian.clone());
        that.angle = cartesian.clone();
        that.anglePoint.typeAttr = "angle";

        if (that.centerPoint) that.centerPoint.show = true
        if (that.edgePoint) that.edgePoint.show = true
        if (that.anglePoint) that.anglePoint.show = true



        // 初始化位置属性
        that.position = cartesian.clone();
        that.edgePosition = cartesian.clone();
        that.anglePosition = cartesian.clone();

        that.isSettingRadius = true;
        that.prompt.update(evt.position, "拖动鼠标调整半径，松开左键确认");
      } else if (that.isSettingRadius) {
        // 结束设置半径
        that.isSettingRadius = false;
        that.edge = cartesian;
        that.edgePoint.position.setValue(cartesian);
        that.edgePosition = cartesian.clone();
        that.radius = Cesium.Cartesian3.distance(that.center, that.edge);

        // 计算起始角度（相对于正北方向）
        const heading = that.calculateHeading(that.center, that.edge);
        that.startAngle = heading;
        that.endAngle = heading; // 初始结束角度与起始角度相同

        // 创建扇形实体
        that.entity = that.createSector();

        that.isSettingAngle = true;
        that.prompt.update(evt.position, "拖动鼠标调整角度，松开左键确认");
      } else if (that.isSettingAngle) {
        // 结束设置角度
        that.isSettingAngle = false;
        that.angle = cartesian;
        that.anglePoint.position.setValue(cartesian);
        that.anglePosition = cartesian.clone();

        // 计算结束角度
        const heading = that.calculateHeading(that.center, that.angle);
        that.endAngle = heading;

        // 确保角度范围在0-2π之间
        if (that.endAngle < that.startAngle) {
          that.endAngle += Math.PI * 2;
        }

        // 更新扇形实体
        that.entity = that.createSector();

        // 标绘完成，隐藏控制点和提示
        that.endCreate();
        if (callback) callback(that.entity);
        that.trigger('endCreate', that, that.entity);

        // 启用扇形点击编辑功能
        that.enableClickToEdit();
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    // 鼠标移动事件 - 动态绘制
    this.handler.setInputAction(function (evt) {
      that.lastMousePosition = evt.endPosition;
      const cartesian = that.getCatesian3FromPX(evt.endPosition, that.viewer, []);

      // 检查是否获得有效坐标
      if (!cartesian || that.hasNaNComponent(cartesian)) {
        return;
      }

      if (!that.centerPoint) {
        that.prompt.update(evt.endPosition, "单击确定扇形中心点");
      } else if (that.isSettingRadius) {
        // 正在调整半径
        that.prompt.update(evt.endPosition, "拖动鼠标调整半径，松开左键确认");
        that.edgePoint.position.setValue(cartesian);
        that.edge = cartesian.clone();
        that.edgePosition = cartesian.clone();
        that.radius = Cesium.Cartesian3.distance(that.center, that.edge);

        // 更新扇形显示
        if (that.entity) {
          that.entity = that.createSector();
        }
      } else if (that.isSettingAngle) {
        // 正在调整角度
        that.prompt.update(evt.endPosition, "拖动鼠标调整角度，松开左键确认");
        that.anglePoint.position.setValue(cartesian);
        that.angle = cartesian.clone();
        that.anglePosition = cartesian.clone();

        // 计算结束角度
        const heading = that.calculateHeading(that.center, that.angle);
        that.endAngle = heading;

        // 确保角度范围在0-2π之间
        if (that.endAngle < that.startAngle) {
          that.endAngle += Math.PI * 2;
        }

        // 更新扇形显示
        that.entity = that.createSector();
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // 左键释放事件 - 结束当前操作
    this.handler.setInputAction(function (evt) {
      if (that.isSettingRadius) {
        that.prompt.update(evt.position, "拖动鼠标调整角度，松开左键确认");
      }
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }

  /**
   * 启用扇形点击编辑功能
   */
  enableClickToEdit() {
    if (!this.viewer || !this.entity) return;

    // 确保扇形实体有objId和type属性
    if (this.entity) {
      this.entity.objId = this.entity.objId || Date.now();
      this.entity.type = "sector";
    }

    const that = this;
    // 创建点击事件处理器（如果尚未创建）
    if (!this.clickHandler) {
      this.clickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    } else {
      // 清除之前的事件处理
      this.clickHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }

    // 绑定LEFT_CLICK事件监听器
    this.clickHandler.setInputAction(function (click) {
      const pickedObject = that.viewer.scene.pick(click.position);
      if (Cesium.defined(pickedObject) && pickedObject.id === that.entity) {
        console.log('点击了扇形实体');
        // 检查是否已经在编辑状态
        if (that.state !== "editing" && that.state !== "startEdit") {
          that.startEdit();
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  /**
   * 结束编辑
   * @param {Function} callback 结束回调函数
   */
  endEdit(callback) {
    // 隐藏控制点
    if (this.centerPoint) this.centerPoint.show = false;
    if (this.edgePoint) this.edgePoint.show = false;
    if (this.anglePoint) this.anglePoint.show = false;

    // 销毁编辑事件处理器
    if (this.modifyHandler) {
      this.modifyHandler.destroy();
      this.modifyHandler = null;
    }

    // 禁用地球表面点击事件处理
    this.disableSurfaceClickHandler();

    this.forbidDrawWorld(false);
    this.state = "endEdit";
    if (this.entity) {
      // 创建自定义事件并传递实体数据
      const event = new CustomEvent('cesium-entity-sx-editend', {
        detail: {
          entityObj: this,
          entity: this.entity
        }
      });
      window.dispatchEvent(event);
    }
    // 重新启用点击编辑功能
    this.enableClickToEdit();

    if (callback) callback(this.entity);

    // 触发 endEdit 事件
    this.trigger('endEdit', this, this.entity);

    // 触发 drawTool 的 endEditFun 事件
    if (this.viewer.drawTool && typeof this.viewer.drawTool.endEditFun === 'function') {
      this.viewer.drawTool.endEditFun(this, this.entity);
    }
  }

  /**
   * 开始编辑
   * @param {Function} callback 回调函数
   */
  startEdit(callback) {
    // 确保当前有实体且不处于编辑状态
    if (!this.entity || this.state === "editing") {
      return;
    }

    // 重置状态
    this.state = "startEdit";

    // 销毁现有编辑处理器
    if (this.modifyHandler) {
      this.modifyHandler.destroy();
      this.modifyHandler = null;
    }

    // 创建新的编辑处理器
    this.modifyHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

    const that = this;

    // 显示控制点
    if (that.edgePoint) that.edgePoint.show = true;
    if (that.centerPoint) that.centerPoint.show = true;
    if (that.anglePoint) that.anglePoint.show = true;

    // 触发 startEdit 事件
    this.trigger('startEdit', this, this.entity);

    // 触发 drawTool 的 startEditFun 事件
    if (this.viewer.drawTool && typeof this.viewer.drawTool.startEditFun === 'function') {
      this.viewer.drawTool.startEditFun(this, this.entity);
    }

    // 鼠标左键按下事件 - 开始拖动控制点
    this.modifyHandler.setInputAction(function (evt) {
      if (!that.entity) return;
      that.state = "editing";
      const pick = that.viewer.scene.pick(evt.position);
      if (Cesium.defined(pick) && pick.id) {
        if (!pick.id.objId) that.modifyPoint = pick.id;
        that.forbidDrawWorld(true);
      } else {
        // 如果点击的不是控制点，结束编辑
        that.endEdit();
      }

    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    // 鼠标移动事件 - 拖动控制点
    this.modifyHandler.setInputAction(function (evt) {
      if (!that.modifyPoint) return;
      const cartesian = that.getCatesian3FromPX(evt.endPosition, that.viewer);
      if (!cartesian) return;
      that.state = "editing";
      if (that.modifyPoint.typeAttr === "center") {
        const subtract = Cesium.Cartesian3.subtract(
          cartesian,
          that.position,
          new Cesium.Cartesian3()
        );
        that.position = cartesian;
        that.center = cartesian.clone();
        that.centerPoint.position.setValue(that.position);

        that.edgePosition = Cesium.Cartesian3.add(
          that.edgePosition,
          subtract,
          new Cesium.Cartesian3()
        );
        that.edge = that.edgePosition.clone();
        that.edgePoint.position.setValue(that.edgePosition);

        that.anglePosition = Cesium.Cartesian3.add(
          that.anglePosition,
          subtract,
          new Cesium.Cartesian3()
        );
        that.angle = that.anglePosition.clone();
        that.anglePoint.position.setValue(that.anglePosition);

        // 更新扇形实体
        that.entity = that.createSector();
      } else if (that.modifyPoint.typeAttr === "edge") {
        that.edgePosition = cartesian;
        that.edge = cartesian.clone();
        that.edgePoint.position.setValue(that.edgePosition);
        that.radius = Cesium.Cartesian3.distance(that.edgePosition, that.position);

        // 更新扇形
        that.entity = that.createSector();
      } else if (that.modifyPoint.typeAttr === "angle") {
        that.anglePosition = cartesian;
        that.angle = cartesian.clone();
        that.anglePoint.position.setValue(that.anglePosition);
        // 重新计算角度
        that.endAngle = that.calculateHeading(that.center, that.angle);
        // 确保角度范围在0-2π之间
        if (that.endAngle < that.startAngle) {
          that.endAngle += Math.PI * 2;
        }
        // 更新扇形
        that.entity = that.createSector();
      }
      if (callback) callback();
      if (that.entity) {
        // 创建自定义事件并传递实体数据
        const event = new CustomEvent('cesium-entity-sx-editing', {
          detail: {
            entityObj: that,
            entity: that.entity
          }
        });
        window.dispatchEvent(event);
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // 鼠标左键释放事件 - 结束拖动
    this.modifyHandler.setInputAction(function (evt) {
      if (!that.modifyPoint) return;
      that.modifyPoint = null;
      that.forbidDrawWorld(false);
      that.state = "editing";
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }

  /**
   * 禁用扇形点击编辑功能
   */
  disableClickToEdit() {
    if (this.clickHandler) {
      this.clickHandler.destroy();
      this.clickHandler = null;
    }
  }

  /**
   * 启用地球表面点击事件处理
   */
  enableSurfaceClickHandler() {
    if (this.surfaceClickHandler) {
      this.surfaceClickHandler.destroy();
    }

    this.surfaceClickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    const that = this;

    // 左键点击事件
    this.surfaceClickHandler.setInputAction(function (evt) {
      if (that.state !== "startEdit" && that.state !== "editing") {
        return; // 不在编辑状态，不处理
      }

      const pick = that.viewer.scene.pick(evt.position);

      // 如果点击的不是扇形或控制点，结束编辑
      if (!Cesium.defined(pick) || (pick.id !== that.entity &&
        pick.id !== that.centerPoint &&
        pick.id !== that.edgePoint &&
        pick.id !== that.anglePoint)) {
        that.endEdit();
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  /**
   * 禁用地球表面点击事件处理
   */
  disableSurfaceClickHandler() {
    if (this.surfaceClickHandler) {
      this.surfaceClickHandler.destroy();
      this.surfaceClickHandler = null;
    }
  }

  /**
   * 计算两点之间的航向角（相对于正北方向）
   * @param {Cesium.Cartesian3} center 中心点
   * @param {Cesium.Cartesian3} point 目标点
   * @returns {Number} 航向角（弧度）
   */
  calculateHeading(center, point) {
    // 检查输入是否有效
    if (!center || !point || this.hasNaNComponent(center) || this.hasNaNComponent(point)) {
      return 0;
    }

    const cartographicCenter = Cesium.Cartographic.fromCartesian(center);
    const cartographicPoint = Cesium.Cartographic.fromCartesian(point);

    // 计算从中心点到目标点的方向
    const direction = Cesium.Cartesian3.subtract(point, center, new Cesium.Cartesian3());
    Cesium.Cartesian3.normalize(direction, direction);

    // 计算与正北方向的夹角（航向角）
    const up = Cesium.Cartesian3.normalize(center, new Cesium.Cartesian3());
    const east = Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, up, new Cesium.Cartesian3());
    Cesium.Cartesian3.normalize(east, east);
    const north = Cesium.Cartesian3.cross(up, east, new Cesium.Cartesian3());

    // 计算方向向量在东北平面上的投影
    const projection = new Cesium.Cartesian3();
    projection.x = Cesium.Cartesian3.dot(direction, east);
    projection.y = Cesium.Cartesian3.dot(direction, north);

    // 计算航向角（相对于正北方向）
    return Math.atan2(projection.x, projection.y);
  }

  /**
   * 计算三点形成的角度
   * @param {Cesium.Cartesian3} point1 第一个点
   * @param {Cesium.Cartesian3} point2 第二个点
   * @param {Cesium.Cartesian3} center 中心点
   * @returns {Number} 角度（弧度）
   */
  calculateAngle(point1, point2, center) {
    // 计算从中心点到两个点的向量
    const vector1 = Cesium.Cartesian3.subtract(point1, center, new Cesium.Cartesian3());
    const vector2 = Cesium.Cartesian3.subtract(point2, center, new Cesium.Cartesian3());

    // 归一化向量
    Cesium.Cartesian3.normalize(vector1, vector1);
    Cesium.Cartesian3.normalize(vector2, vector2);

    // 计算向量点积
    const dotProduct = Cesium.Cartesian3.dot(vector1, vector2);

    // 确保点积在有效范围内（-1到1）
    const clampedDotProduct = Math.max(-1.0, Math.min(1.0, dotProduct));

    // 计算角度（弧度）
    return Math.acos(clampedDotProduct);
  }

  /**
   * 结束标绘
   */
  endCreate() {
    const that = this;
    if (that.handler) {
      that.handler.destroy();
      that.handler = null;
    }
    // 隐藏控制点（编辑时再显示）
    if (that.centerPoint) that.centerPoint.show = false;
    if (that.edgePoint) that.edgePoint.show = false;
    if (that.anglePoint) that.anglePoint.show = false;
    if (that.prompt) {
      that.prompt.destroy();
      that.prompt = null;
    }
    that.state = "endCreate";
    that.isDrawing = false;
    that.isSettingRadius = false;
    that.isSettingAngle = false;

    // 添加objId属性，用于标识实体
    if (that.entity) {
      that.entity.objId = Date.now();
      that.entity.type = "sector"; // 添加类型标识
    }

    // 启用扇形点击编辑功能
    this.enableClickToEdit();

    // 触发 endCreate 事件
    this.trigger('endCreate', this, this.entity);
  }

  /**
   * 结束当前操作（绘制或编辑）
   */
  done() {
    if (this.state === "startCreate" || this.state === "creating") {
      this.destroy();
    } else if (this.state === "startEdit" || this.state === "editing") {
      this.endEdit();
    }
  }

  /**
   * 创建扇形实体
   * @returns {Cesium.Entity} 扇形实体
   */
  createSector() {
    // 移除旧实体
    if (this.entity) {
      this.viewer.entities.remove(this.entity);
    }

    // 检查是否有有效的中心点和半径
    if (!this.center || this.hasNaNComponent(this.center) || this.radius <= 0) {
      return null;
    }

    const that = this;
    // 计算扇形顶点
    const positions = this.generateSectorPositions(that.center, that.radius, that.startAngle, that.endAngle);
    // 检查生成的位置是否有效
    if (!positions || positions.length < 3 || positions.some(p => this.hasNaNComponent(p))) {
      console.warn('无效的扇形位置，无法创建扇形');
      return null;
    }
    // 创建扇形面实体
    const entity = this.viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(positions),
        height: 0,
        heightReference: this.style.heightReference || Cesium.HeightReference.NONE,
        fill: this.style.fill !== undefined ? this.style.fill : true,
        material: this.style.color
          ? Cesium.Color.fromCssColorString(this.style.color).withAlpha(this.style.colorAlpha || 0.5)
          : Cesium.Color.RED.withAlpha(0.5),
        outline: this.style.outline !== undefined ? this.style.outline : true,
        outlineColor: this.style.outlineColor
          ? Cesium.Color.fromCssColorString(this.style.outlineColor)
          : Cesium.Color.BLACK,
        outlineWidth: this.style.outlineWidth || 1,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });

    // 恢复实体的标识属性
    if (this.entity && this.entity.objId) {
      entity.objId = this.entity.objId;
      entity.type = "sector";
    }

    return entity;
  }
  /**
      * 更新扇形的中心点位置
      * @param {Cesium.Cartesian3} newCenter 新的中心点坐标
      */
  updateSectorCenter(newCenter) {
    // 更新中心点坐标
    this.center = newCenter;

    // 重新生成扇形实体
    this.entity = this.createSector();

    // 更新控制点的位置
    this.centerPoint.position.setValue(newCenter);

    // 计算边缘点和角度控制点相对于新中心点的位置
    const subtract = Cesium.Cartesian3.subtract(
      newCenter,
      this.position,
      new Cesium.Cartesian3()
    );

    this.edgePosition = Cesium.Cartesian3.add(
      this.edgePosition,
      subtract,
      new Cesium.Cartesian3()
    );
    this.edge = this.edgePosition.clone();
    this.edgePoint.position.setValue(this.edgePosition);

    this.anglePosition = Cesium.Cartesian3.add(
      this.anglePosition,
      subtract,
      new Cesium.Cartesian3()
    );
    this.angle = this.anglePosition.clone();
    this.anglePoint.position.setValue(this.anglePosition);

    // 触发自定义事件，通知其他部分扇形已更新
    if (this.entity) {
      const event = new CustomEvent('cesium-entity-sx-editing', {
        detail: {
          entityObj: this,
          entity: this.entity
        }
      });
      window.dispatchEvent(event);
    }
  }

  /**
   * 生成扇形的顶点坐标
   * @param {Cesium.Cartesian3} center 中心点
   * @param {Number} radius 半径
   * @param {Number} startAngle 起始角度（弧度）
   * @param {Number} endAngle 结束角度（弧度）
   * @returns {Array<Cesium.Cartesian3>} 顶点坐标数组
   */
  generateSectorPositions(center, radius, startAngle, endAngle) {
    // 检查输入是否有效
    if (!center || this.hasNaNComponent(center) || radius <= 0) {
      return [];
    }

    const positions = [center]; // 起点为中心点

    // 确保角度范围正确
    if (startAngle > endAngle) {
      const temp = startAngle;
      startAngle = endAngle;
      endAngle = temp;
    }

    // 角度步长（控制扇形平滑度）
    const step = 0.05;
    const numPoints = Math.ceil((endAngle - startAngle) / step);

    // 生成扇形边缘点
    for (let i = 0; i <= numPoints; i++) {
      const angle = startAngle + i * step;

      // 使用经纬度计算方式（更精确）
      const cartographic = Cesium.Cartographic.fromCartesian(center);
      const lat = cartographic.latitude;
      const lon = cartographic.longitude;

      // 计算新点的经纬度
      const newLat = lat + (radius * Math.cos(angle)) / Cesium.Ellipsoid.WGS84.maximumRadius;
      const newLon = lon + (radius * Math.sin(angle)) / (Cesium.Ellipsoid.WGS84.maximumRadius * Math.cos(lat));

      // 转换为笛卡尔坐标
      const destination = Cesium.Cartesian3.fromRadians(
        newLon,
        newLat,
        cartographic.height
      );

      // 检查生成的坐标是否有效
      if (!this.hasNaNComponent(destination)) {
        positions.push(destination);
      }
    }

    // 确保至少有3个点（中心点和两个边缘点）
    if (positions.length < 3) {
      return [];
    }

    positions.push(center); // 闭合扇形
    return positions;
  }

  /**
   * 获取扇形坐标信息
   * @param {Boolean} isWgs84 是否返回经纬度坐标
   * @returns {Array} 坐标数组
   */
  getPositions(isWgs84) {
    const positions = [this.center, this.edge, this.angle];
    return isWgs84
      ? util.cartesiansToLnglats(positions, this.viewer)
      : positions;
  }

  /**
   * 获取当前样式配置
   * @returns {Object} 样式配置
   */
  getStyle() {
    if (!this.entity) return {};
    const polygon = this.entity.polygon;
    const color = polygon.material.color.getValue();
    const outlineColor = polygon.outlineColor.getValue();
    let colorStr = new Cesium.Color(
      color.red,
      color.green,
      color.blue,
      1
    ).toCssHexString();

    return {
      // color: Cesium.Color.fromRgba(convertedColor).toCssHexString(),
      color: colorStr,
      colorAlpha: color.alpha,
      outline: polygon.outline.getValue(),
      outlineColor: Cesium.Color.fromRgba(outlineColor).toCssHexString(),
      outlineWidth: polygon.outlineWidth._value,
      heightReference: polygon.heightReference.getValue()
    };
  }

  /**
   * 设置扇形样式
   * @param {Object} style 样式配置
   */
  setStyle(style) {
    if (!style || !this.entity) return;
    const polygon = this.entity.polygon;

    if (style.color) {
      const color = Cesium.Color.fromCssColorString(style.color)
        .withAlpha(style.colorAlpha !== undefined ? style.colorAlpha : 0.5);
      polygon.material = color;
    }

    if (style.outline !== undefined) polygon.outline = style.outline;
    if (style.outlineColor) {
      polygon.outlineColor = Cesium.Color.fromCssColorString(style.outlineColor);
    }
    if (style.outlineWidth) polygon.outlineWidth = style.outlineWidth;
    if (style.heightReference !== undefined) {
      polygon.heightReference = style.heightReference;
    }

    this.style = { ...this.style, ...style };
  }

  /**
   * 销毁扇形标绘
   */
  destroy() {
    // this.disableClickToEdit();
    this.disableSurfaceClickHandler();

    if (this.entity) {
      this.viewer.entities.remove(this.entity);
    }
    if (this.centerPoint) {
      this.viewer.entities.remove(this.centerPoint);
    }
    if (this.edgePoint) {
      this.viewer.entities.remove(this.edgePoint);
    }
    if (this.anglePoint) {
      this.viewer.entities.remove(this.anglePoint);
    }
    if (this.handler) {
      this.handler.destroy();
      this.handler = null;
    }
    if (this.modifyHandler) {
      this.modifyHandler.destroy();
      this.modifyHandler = null;
    }
    if (this.prompt) {
      this.prompt.destroy();
      this.prompt = null;
    }
    this.state = null;
    this.isDrawing = false;
    this.isSettingRadius = false;
    this.isSettingAngle = false;
  }

  /**
   * 从屏幕坐标获取笛卡尔坐标（改进版，确保鼠标位置与扇形边缘一致）
   * @param {Cesium.Cartesian2} screenPosition 屏幕坐标
   * @param {Cesium.Viewer} viewer Cesium查看器
   * @param {Array} excludeEntities 排除的实体
   * @returns {Cesium.Cartesian3|null} 笛卡尔坐标或null
   */
  getCatesian3FromPX(screenPosition, viewer, excludeEntities) {
    // 首先尝试从地形获取坐标
    const terrainSamplePositions = [
      viewer.camera.pickEllipsoid(screenPosition, viewer.scene.globe.ellipsoid)
    ];

    if (terrainSamplePositions[0]) {
      return terrainSamplePositions[0];
    }

    // 如果地形上没有，尝试从3D Tiles获取
    const ray = viewer.camera.getPickRay(screenPosition);
    const result = viewer.scene.globe.pick(ray, viewer.scene);

    if (result) {
      return result;
    }

    // 最后尝试从其他实体获取
    const pick = viewer.scene.pick(screenPosition);
    if (pick && pick.id && !excludeEntities.includes(pick.id)) {
      return viewer.camera.pickEllipsoid(screenPosition, viewer.scene.globe.ellipsoid);
    }

    // 如果都没有，返回null
    return null;
  }

  /**
   * 检查坐标是否包含NaN值
   * @param {Cesium.Cartesian3} cartesian 笛卡尔坐标
   * @returns {Boolean} 如果包含NaN值返回true，否则返回false
   */
  hasNaNComponent(cartesian) {
    return (
      !cartesian ||
      isNaN(cartesian.x) ||
      isNaN(cartesian.y) ||
      isNaN(cartesian.z)
    );
  }

  /**
   * 创建点实体
   * @param {Cesium.Cartesian3} position 点的位置
   * @returns {Cesium.Entity} 点实体
   */
  createPoint(position) {
    return this.viewer.entities.add({
      position: position,
      point: {
        pixelSize: 8,
        color: Cesium.Color.BLUE,
        outline: false,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 1
      },
      show: false
    });
  }

  /**
   * 禁止或允许地图操作
   * @param {Boolean} isForbid 是否禁止
   */
  forbidDrawWorld(isForbid) {
    this.viewer.scene.screenSpaceCameraController.enableRotate = !isForbid;
    this.viewer.scene.screenSpaceCameraController.enableTranslate = !isForbid;
    this.viewer.scene.screenSpaceCameraController.enableZoom = !isForbid;
    this.viewer.scene.screenSpaceCameraController.enableTilt = !isForbid;
    this.viewer.scene.screenSpaceCameraController.enableLook = !isForbid;
  }

  /**
   * 通过坐标数组构建
   * @param {Array|Object} positionsOrParams 位置参数
   * @param {Function} callback 绘制成功后回调函数
  */
  createByPositions(positionsOrParams, callback) {
    if (!positionsOrParams) return;

    this.state = "startCreate";

    // 检查是否是扇形参数对象（包含center, radius, startAngle, endAngle）
    if (positionsOrParams.center && positionsOrParams.radius !== undefined) {
      // 从参数对象创建扇形
      this.center = positionsOrParams.center;
      this.radius = positionsOrParams.radius;
      this.startAngle = Cesium.Math.toRadians(positionsOrParams.startAngle || 0);
      this.endAngle = Cesium.Math.toRadians(positionsOrParams.endAngle || 0);

      // 确保角度范围在0-2π之间
      if (this.endAngle < this.startAngle) {
        this.endAngle += Math.PI * 2;
      }

      // 使用更精确的方法计算边缘点和角度点
      // 参考createEllipse.js中的计算方式
      const ellipsoid = this.viewer.scene.globe.ellipsoid;
      const centerCartographic = ellipsoid.cartesianToCartographic(this.center);

      // 计算起始角度方向的边缘点
      const startBearing = this.startAngle;
      const startDestination = Cesium.Cartesian3.fromDegrees(
        Cesium.Math.toDegrees(centerCartographic.longitude) + (this.radius * Math.sin(startBearing) / (6378137.0 * Math.cos(centerCartographic.latitude))),
        Cesium.Math.toDegrees(centerCartographic.latitude) + (this.radius * Math.cos(startBearing) / 6378137.0),
        centerCartographic.height,
        ellipsoid
      );
      this.edge = startDestination;

      // 计算结束角度方向的角度点
      const endBearing = this.endAngle;
      const endDestination = Cesium.Cartesian3.fromDegrees(
        Cesium.Math.toDegrees(centerCartographic.longitude) + (this.radius * Math.sin(endBearing) / (6378137.0 * Math.cos(centerCartographic.latitude))),
        Cesium.Math.toDegrees(centerCartographic.latitude) + (this.radius * Math.cos(endBearing) / 6378137.0),
        centerCartographic.height,
        ellipsoid
      );


      this.angle = endDestination;


      // 创建控制点
      this.centerPoint = this.createPoint(this.center);
      this.centerPoint.typeAttr = "center";
      this.edgePoint = this.createPoint(this.edge);
      this.edgePoint.typeAttr = "edge";
      this.anglePoint = this.createPoint(this.angle);
      this.anglePoint.typeAttr = "angle";

      this.entity = this.createSector();
      this.entity.objId = this.objId;
    } else {
      // 从坐标数组创建扇形的原有逻辑保持不变
      let positions = [];
      if (Array.isArray(positionsOrParams)) {
        const isCartesian3 = positionsOrParams[0] instanceof Cesium.Cartesian3;
        if (isCartesian3) {
          positions = positionsOrParams;
        } else {
          positions = util.lnglatsToCartesians(positionsOrParams);
        }
      }

      if (!positions || positions.length < 1) return;

      this.center = positions[0].clone();
      this.edge = positions[1].clone();
      this.angle = positions[2].clone();

      this.radius = Cesium.Cartesian3.distance(this.center, this.edge);
      this.startAngle = this.calculateHeading(this.center, this.edge);
      this.endAngle = this.calculateHeading(this.center, this.angle);

      // 确保角度范围在0-2π之间
      if (this.endAngle < this.startAngle) {
        this.endAngle += Math.PI * 2;
      }



      // 创建控制点
      this.centerPoint = this.createPoint(this.center);
      this.centerPoint.typeAttr = "center";
      this.edgePoint = this.createPoint(this.edge);
      this.edgePoint.typeAttr = "edge";
      this.anglePoint = this.createPoint(this.angle);
      this.anglePoint.typeAttr = "angle";
      this.entity = this.createSector();
    }

    this.position = this.center.clone();
    this.edgePosition = this.edge.clone();
    this.anglePosition = this.angle.clone();
    this.state = "endCreate";
    if (callback) callback(this.entity);
  }



}
export default CreateSector;